package com.ytjj.qmyx.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.utils.HttpClientUtil;
import com.ytjj.qmyx.admin.config.SupplyApiConfig;
import com.ytjj.qmyx.admin.dao.OrdersDao;
import com.ytjj.qmyx.admin.dao.OrdersTransferManageDao;
import com.ytjj.qmyx.admin.dao.ProductDao;
import com.ytjj.qmyx.admin.dao.ProductSpecDao;
import com.ytjj.qmyx.admin.model.request.OrderQueryRequest;
import com.ytjj.qmyx.admin.model.response.OrdersTransferCompareResponse;
import com.ytjj.qmyx.admin.model.response.OrdersTransferResponse;
import com.ytjj.qmyx.admin.service.OrdersTransferManageService;
import com.ytjj.qmyx.mall.client.MallClient;
import com.ytjj.qmyx.mall.mapper.OrdersTransferManageMapper;
import com.ytjj.qmyx.mall.mapper.ProductMapper;
import com.ytjj.qmyx.mall.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author jiawei
 * @date 2023年09月14日 10:09
 * @describe
 */
@Service
@Slf4j
public class OrdersTransferManageServiceImpl implements OrdersTransferManageService {
    @Autowired
    private OrdersTransferManageDao ordersTransferManageDao;
    @Autowired
    private OrdersTransferManageMapper ordersTransferManageMapper;
    @Autowired
    private SupplyApiConfig supplyApiConfig;
    @Autowired
    private ProductDao productDao;
    @Autowired
    private OrdersDao ordersDao;
    @Autowired
    private MallClient mallClient;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductSpecDao productSpecDao;

    @Override
    public CommonPage getOrdersTransferPage(Integer status, Integer pageNum, Integer pageSize) {
        List<OrdersTransferCompareResponse> resultData = new ArrayList<>();
        PageHelper.startPage(pageNum, pageSize);
        List<OrdersTransferResponse> ordersTransferPage = ordersTransferManageDao.getOrdersTransferPage(status);
        if(CollectionUtils.isEmpty(ordersTransferPage)){
            return CommonPage.restPage(ordersTransferPage);
        }
        List<Integer> orangeBankerIds = ordersTransferPage.stream().map(e -> e.getOrangeBankerId()).collect(Collectors.toList());
        List<Integer> targetBankerIds = ordersTransferPage.stream().map(e -> e.getTargetBankerId()).collect(Collectors.toList());
        List<Integer> bankerIds = new ArrayList<>();
        bankerIds.addAll(orangeBankerIds);
        bankerIds.addAll(targetBankerIds);
        //查询供应商名称
        BankerRequest bankerRequest = new BankerRequest();
        bankerRequest.setBankerIdList(bankerIds);
        String json = JSON.toJSONString(bankerRequest);
        String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/getBankerMsg", json, supplyApiConfig.getHeadsMap());
        List<BankerResponse> bankerResponses = JSONObject.parseArray(result, BankerResponse.class);
        Map<Integer, List<BankerResponse>> bankers = bankerResponses.stream().collect(Collectors.groupingBy(e -> e.getBankerId()));
        for (OrdersTransferResponse response : ordersTransferPage) {
            OrdersTransferCompareResponse entity = new OrdersTransferCompareResponse();
            OrdersTransferCompareResponse.ProductDetail orgProductDetail = new OrdersTransferCompareResponse().new ProductDetail();
            OrdersTransferCompareResponse.ProductDetail transProductDetail = new OrdersTransferCompareResponse().new ProductDetail();
            List<BankerResponse> orgBankers = bankers.get(response.getOrangeBankerId());
            //原商品
            orgProductDetail.setProductId(response.getOrangeProductId());
            orgProductDetail.setProductName(response.getOrangeProductName());
            orgProductDetail.setSupplyProductId(response.getOrangeSupplyProductId());
            if(!CollectionUtils.isEmpty(orgBankers)){
                BankerResponse bankerResponse = orgBankers.get(0);
                orgProductDetail.setBankerInfo(bankerResponse.getBankerId() + " " + bankerResponse.getBankerName());
            }
            orgProductDetail.setProductImg(response.getOrangeProductImg());
            if(StringUtils.isNotEmpty(response.getOrgSpecJson())){
                orgProductDetail.setProductSpec(JSON.parseArray(response.getOrgSpecJson(), ProductSpec.class));
            }
            //转单商品
            List<BankerResponse> targetBankers = bankers.get(response.getTargetBankerId());
            transProductDetail.setProductId(response.getTargetProductId());
            transProductDetail.setProductName(response.getTargetProductName());
            transProductDetail.setProductImg(response.getTargetProductImg());
            transProductDetail.setSupplyProductId(response.getTargetSupplyProductId());
            if(!CollectionUtils.isEmpty(targetBankers)){
                BankerResponse bankerResponse = targetBankers.get(0);
                transProductDetail.setBankerInfo(bankerResponse.getBankerId() + " " + bankerResponse.getBankerName());
            }
            if(StringUtils.isNotEmpty(response.getTargetSpecJson())){
                transProductDetail.setProductSpec(JSON.parseArray(response.getTargetSpecJson(),ProductSpec.class));
            }
            entity.setTransferNum(response.getTransferNum());
            entity.setStatus(response.getStatus());
            entity.setCreateTime(response.getCreateTime());
            entity.setUpdateTime(response.getUpdateTime());
            entity.setOrgProduct(orgProductDetail);
            entity.setTransferProduct(transProductDetail);
            entity.setId(response.getId());
            resultData.add(entity);
        }
        return CommonPage.restPage(resultData);
    }

    @Override
    public Integer addOrUpdateOrdersTransfer(OrdersTransferCompareResponse request) {
        OrdersTransferCompareResponse.ProductDetail orgProduct = request.getOrgProduct();
        OrdersTransferCompareResponse.ProductDetail targetProduct = request.getTransferProduct();
        Integer result = 0;
        if(null == orgProduct || null == orgProduct.getProductId() || null == targetProduct || null == targetProduct.getProductId()){
            throw new ApiException("原商品或目标商品数据不全！");
        }
        List<ProductSpec> productSpec = orgProduct.getProductSpec();
        List<ProductSpec> targetSpec = targetProduct.getProductSpec();
        if(CollectionUtils.isEmpty(productSpec) || CollectionUtils.isEmpty(targetSpec)){
            throw new ApiException("原商品或目标商品规格数据不全！");
        }
        Integer productId = targetProduct.getProductId();
        Product productById = productDao.getProductById(productId);
        if (Integer.valueOf(productById.getStatus()) != 1) {
            throw new ApiException("操作失败，转单商品当前不是上架状态！");
        }
        if(orgProduct.getProductId().equals(targetProduct.getProductId())){
            throw new ApiException("原商品和目标商品不能是同一个！");
        }
        OrdersTransferManage ordersTransferManage = new OrdersTransferManage();
        ordersTransferManage.setTransferNum(targetProduct.getCurTransferNum());
        ordersTransferManage.setOrangeProductId(orgProduct.getProductId());
        ordersTransferManage.setOrangeProductSpec(JSON.toJSONString(productSpec));
        ordersTransferManage.setTargetProductId(targetProduct.getProductId());
        ordersTransferManage.setTargetProductSpec(JSON.toJSONString(targetSpec));
        //新增
        if(request.getId() == null){
            //当前是否已存在计划
            OrdersTransferManageExample example = new OrdersTransferManageExample();
            example.createCriteria().andOrangeProductIdEqualTo(orgProduct.getProductId()).andTargetProductIdEqualTo(targetProduct.getProductId()).andIsDeletedEqualTo(0);
            List<OrdersTransferManage> ordersTransferManages = ordersTransferManageMapper.selectByExample(example);
            if(!CollectionUtils.isEmpty(ordersTransferManages)){
                throw new ApiException("当前选择的商品转单任务已存在，请勿重复添加！");
            }
            result = ordersTransferManageMapper.insertSelective(ordersTransferManage);
        }else {//修改
            ordersTransferManage.setId(request.getId());
            ordersTransferManage.setUpdateTime(request.getUpdateTime());
            result = ordersTransferManageMapper.updateByPrimaryKeySelective(ordersTransferManage);
        }
        return result;
    }

    @Override
    public Integer delTransferItem(List<Integer> ids) {
        OrdersTransferManage ordersTransferManage = new OrdersTransferManage();
        AtomicReference<Integer> result = new AtomicReference<>(0);
        ids.forEach(e->{
            ordersTransferManage.setId(e);
            ordersTransferManage.setIsDeleted(1);
            ordersTransferManage.setUpdateTime(new Date());
            result.updateAndGet(v -> v + ordersTransferManageMapper.updateByPrimaryKeySelective(ordersTransferManage));
        });
        return result.get();
    }

    @Override
    public Integer updateTransferStatus(List<Integer> ids) {
        AtomicReference<Integer> result = new AtomicReference<>(0);
        ids.forEach(e->result.updateAndGet(v -> v + ordersTransferManageDao.updateTransferStatus(e)));
        return result.get();
    }

    @Override
    public Integer getUnPushOrdersNum(Integer id) {
        List<OrdersInfo> unPushOrders = getUnPushOrders(id);
        return unPushOrders.size();
    }

    @Override
    public List<OrdersInfo> getUnPushOrders(Integer id) {
        List<OrdersInfo> childOrderNos = new ArrayList<>();
        OrdersTransferManage ordersTransferManage = ordersTransferManageMapper.selectByPrimaryKey(id);
        if(ordersTransferManage == null || ordersTransferManage.getIsDeleted() == 1){
            throw new ApiException("转单任务不存在！");
        }
        List<OrdersInfo> ordersInfos = ordersDao.getUnDeliveryByProductId(ordersTransferManage.getOrangeProductId());
        if(!CollectionUtils.isEmpty(ordersInfos)){
            Map<String, OrdersInfo> map = ordersInfos.stream().collect(Collectors.toMap(OrdersInfo::getChildOrderNo, Function.identity()));
            OrderQueryRequest orderQueryRequest = new OrderQueryRequest();
            orderQueryRequest.setChildOrderNo(new ArrayList<>(map.keySet()));
            String jsonStr = JSONObject.toJSONString(orderQueryRequest);
            String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/selectByChildOrderNo", jsonStr, supplyApiConfig.getHeadsMap());
            if(StringUtils.isNotEmpty(resultJson)){
                //未推单数
                List<String> childOrderNoList = JSONArray.parseArray(resultJson, String.class);
                for (String s : childOrderNoList) {
                    OrdersInfo ordersInfo = map.get(s);
                    if(null != ordersInfo){
                        childOrderNos.add(ordersInfo);
                    }
                }
            }
        }
        return childOrderNos;
    }

    @Override
    public CommonResult toTransferOrders(Integer id,Integer num) {
        List<OrdersInfo> unPushOrders = getUnPushOrders(id);
        if(null == num || num == 0){
            throw new ApiException("转单数必须大于0！");
        }
        if(CollectionUtils.isEmpty(unPushOrders) || unPushOrders.size() < num){
            throw new ApiException("当前可转单数是:" + unPushOrders.size() + "，不足" + num + "单");
        }
        List<OrdersInfo> ordersInfos = unPushOrders.subList(0, num);
        new Thread(()->{
            for (OrdersInfo unPushOrder : ordersInfos) {
                mallClient.toTransferOrders(unPushOrder.getOrderId(),id);
            }
        }).start();
        return CommonResult.success();
    }

    @Override
    public OrdersTransferCompareResponse.ProductDetail getProductInfo(Integer productId) {
        OrdersTransferCompareResponse.ProductDetail productDetail = new OrdersTransferCompareResponse().new ProductDetail();
        Product product = productMapper.selectByPrimaryKey(productId);
        if(null == product){
            return null;
        }
        BeanUtils.copyProperties(product,productDetail);
        //查询供应商名称
        BankerRequest bankerRequest = new BankerRequest();
        bankerRequest.setBankerIdList(Arrays.asList(product.getBankerId()));
        String json = JSON.toJSONString(bankerRequest);
        String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/getBankerMsg", json, supplyApiConfig.getHeadsMap());
        List<BankerResponse> bankerResponses = JSONObject.parseArray(result, BankerResponse.class);
        //供应商
        if(!CollectionUtils.isEmpty(bankerResponses)){
            BankerResponse banker = bankerResponses.get(0);
            productDetail.setBankerInfo(banker.getBankerId()+" "+banker.getBankerName());
        }
        //规格
        List<ProductSpec> productSpecs = productSpecDao.selectByProductIds(Arrays.asList(product.getId()));
        productDetail.setProductSpec(productSpecs);
        productDetail.setProductId(product.getId());
        return productDetail;
    }
}
